import { Login } from "../../api/login";
import { getToken, setToken, removeToken, getNickName, setNickName } from "../../utils/app";

const app = {
  namespaced: true,
  state: {
    leftNavIsCollapsed: JSON.parse(sessionStorage.getItem("leftNavIsCollapsed")) || false,
    token: getToken("admin_token") || "",
    nickname: getNickName("nickname") || "匿名"
  },
  mutations: {
    TOGGLE_LEFT_NAV_COLLAPSE_STATUS(state, value) {
      state.leftNavIsCollapsed = !state.leftNavIsCollapsed;
      sessionStorage.setItem("leftNavIsCollapsed", JSON.stringify(state.leftNavIsCollapsed));
    },
    SET_TOKEN(state, value) {
      state.token = value.token;
      setToken(value.token, value.expire);
    },
    SET_NICKNAME(state, value) {
      state.nickname = value;
      setNickName(value);
    },
    LOGOUT(state, value) {
      console.log("LOGOUT");
      state.token = "";
      state.nickname = "";
      removeToken();
      setNickName("");
    }
  },
  actions: {
    TOGGLE_LEFT_NAV_COLLAPSE_STATUS($store, payload) {
      // console.log("$store:", $store); // ctx: {getters: {…}, state: {…}, rootGetters: {…}, dispatch: ƒ, commit: ƒ, …}
      $store.commit("TOGGLE_LEFT_NAV_COLLAPSE_STATUS");
    },
    async login($store, payload) {
      const res = await Login(payload);
      $store.commit("SET_TOKEN", { token: res.token, expire: res.expire });
      $store.commit("SET_NICKNAME", res.nickname);
      return res;
    },
    async LOGOUT($store) {
      $store.commit("LOGOUT");
    }
  }
};

export default app;
